package com.huazhi.wzsnw.dtu;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DtuServer {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup works = new NioEventLoopGroup();

    public void bind() {
        int port = 8090;
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, works).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new DtuServerHandle());
                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            if (channelFuture.isSuccess()) {
                System.out.println("服务端启动成功");
            }
            //关闭服务器
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            works.shutdownGracefully();
            System.out.println("服务端已关闭");

        }
    }
}
